﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Forest.Cat.Domain.Entities;
using Forest.Cat.Domain.Shared.Security;
using Forest.Core;
using Forest.Core.Data;
using Forest.Cat.Domain.Shared;

namespace Forest.Cat.Domain.Services.Jobseekers
{
    public partial class JobseekerRegistrationService : IJobseekerRegistrationService
    {

        private readonly IJobseekerService _jobseekerService;
        private readonly IEncryptionService _encryptionService;
        private readonly IRepository<Jobseeker> _jobseekerRepository;
        private readonly IGenerateNumberService _generateNumberService;

        public JobseekerRegistrationService(IJobseekerService jobseekerService, IEncryptionService encryptionService,
            IRepository<Jobseeker> jobseekerRepository, IGenerateNumberService generateNumberService)
        {
            _jobseekerService = jobseekerService;
            _encryptionService = encryptionService;
            _jobseekerRepository = jobseekerRepository;
            _generateNumberService = generateNumberService;
        }

        public virtual bool ValidateUser(string email, string password)
        {
            Jobseeker jobseeker = null;

            jobseeker = _jobseekerService.GetUserByEmail(email);

            if (jobseeker == null)
                return false;

            string pwd = "";
            switch (jobseeker.PasswordFormat)
            {
                case (int)PasswordFormat.Encrypted:
                    pwd = "";
                    break;
                case (int)PasswordFormat.Hashed:
                    pwd = _encryptionService.CreatePasswordHash(password, jobseeker.PasswordSalt);
                    break;
                default:
                    pwd = password;
                    break;
            }

            bool isValid = pwd == jobseeker.Password;

            if (isValid)
            {
                jobseeker.LastSignedIn = DateTime.Now;
                // Do Update
            }
            return isValid;
        }

        public JobseekerRegistrationResult RegisterJobseeker(JobseekerRegistrationRequest request)
        {
            if (request == null)
                throw new ArgumentNullException("request");

            if (request.Jobseeker == null)
                throw new ArgumentException("Can't load current jobseeker");

            var result = new JobseekerRegistrationResult();

            if (string.IsNullOrWhiteSpace(request.Email))
            {
                result.AddError("邮件地址未提供！");
                return result;
            }

            if (string.IsNullOrWhiteSpace(request.Password))
            {
                result.AddError("密码未提供");
                return result;
            }


            // Validate unique user
            if (_jobseekerService.GetUserByEmail(request.Email) != null)
            {
                result.AddError("邮件已存在");
                return result;
            }

            // at this point request is valid
            request.Jobseeker.Id = CreateId;// 此处需要采番
            request.Jobseeker.Email = request.Email;
            request.Jobseeker.FullName = request.Username; // 此处为对应Fullname
            request.Jobseeker.Password = request.Password;
            request.Jobseeker.DateCreated = DateTime.Now;
            request.Jobseeker.LastSignedIn = DateTime.Now;

            _jobseekerService.InsertUser(request.Jobseeker);

            return result;

        }

        public Guid CreateId
        {
            get
            {
                return _generateNumberService.GenerateId<Jobseeker>(_jobseekerRepository, GenerateType.Jobseeker);
            }
        }

        public PasswordChangeResult ChangePassword(ChangePasswordRequest request)
        {
            if (request == null)
                throw new ArgumentNullException("request");

            var result = new PasswordChangeResult();

            if (String.IsNullOrWhiteSpace(request.Email))
            {
                result.AddError("邮件地址未提供");
                return result;
            }
            if (String.IsNullOrWhiteSpace(request.NewPassword))
            {
                result.AddError("密码未提供");
                return result;
            }

            var user = _jobseekerService.GetUserByEmail(request.Email);
            if (user == null)
            {
                result.AddError("邮件未发现");
                return result;
            }

            var requestIsValid = false;

            if (request.ValidateRequest)
            {
                string oldpwd = "";
                oldpwd = request.OldPassword;

                bool oldpasswordIsValid = oldpwd == user.Password;

                if (!oldpasswordIsValid)
                    result.AddError("旧密码错误");

                if (oldpasswordIsValid)
                    requestIsValid = true;
            }
            else
                requestIsValid = false;

            // at this point request is valid
            if (requestIsValid)
            {
                user.Password = request.NewPassword;

                _jobseekerService.UpdateUser(user);
            }

            return result;
        }

        public void ResetEmail(Jobseeker jobseeker, string newemail)
        {
            if (jobseeker == null)
                throw new ArgumentNullException();

            newemail = newemail.Trim();
            string oldemail = jobseeker.Email;

            if (!CommonHelper.IsValidEmail(newemail))
                throw new Exception("新邮件地址无效");

            if (newemail.Length > 100)
                throw new Exception("新邮件地址太长");

            var jobseeker2 = _jobseekerService.GetUserByEmail(newemail);
            if (jobseeker2 != null && jobseeker.Id != jobseeker2.Id)
                throw new Exception("邮件地址已存在");

            jobseeker.Email = newemail;
            _jobseekerService.UpdateUser(jobseeker);


        }
    }
}
